<?php

namespace App\Http\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
use Eloquent;


class Smscode extends Eloquent {
	use SoftDeletes;
	protected $table = 'smscodes';

	static public function send($mobile,$type){
		$has = self::where('mobile',$mobile)->where('type',$type)->orderBy('created_at','desc')->first();
		if($has && time() - strtotime($has->created_at) < 300){
			return true;
		}
		$code = mt_rand(1000,9999);
		$obj = new self;
		$obj->mobile = $mobile;
		$obj->type = $type;
		$obj->code = $code;
		$obj->save();

		return self::sendSms($mobile,$code);
	}

	static public function verify($mobile,$code,$type){
		$code = self::where('mobile',$mobile)->where('code',$code)->where('type',$type)->first();
		if(!$code){
			return false;
		}
		$code->delete();
		return true;
	}

	static public function sendSms($mobile,$code){
        $host = "https://ali-sms.showapi.com";
	    $path = "/sendSms";
	    $method = "GET";
	    $appcode = "a17ffbb248b04679a6d119edcae99ce3";
	    $headers = array();
	    array_push($headers, "Authorization:APPCODE " . $appcode);
	    $content = json_encode(array(
	    	'verificationCode'=>$code,
	    	'minute'=>5,
	    ));
	    $params = ['tNum'=>'T170317001209','mobile'=>$mobile,'content'=>$content];
	    $bodys = "";
	    $querys = http_build_query($params);
	    $url = $host . $path . "?" . $querys;

	    $curl = curl_init();
	    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
	    curl_setopt($curl, CURLOPT_URL, $url);
	    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	    curl_setopt($curl, CURLOPT_FAILONERROR, false);
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($curl, CURLOPT_HEADER, true);

	    if (1 == strpos("$".$host, "https://"))
	    {
	        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	    }
	    curl_exec($curl);
		$httpCode = curl_getinfo($curl,CURLINFO_HTTP_CODE);
	    if($httpCode==200){
	    	return true;
	    }
	    return false;
    }

}